from snmp_cmds import snmpwalk, snmpget, snmpgetsome, snmptable
from utils import ipTrans, calcuRate, timeTrans
import setting, json, time

# 返回结果是列表，取一整个表，或者结点下所有叶子节点
# res = snmpgetsome(ipaddress='202.119.11.12', oids=['1.3.6.1.2.1.2.2.1.1.1', '1.3.6.1.2.1.2.2.1.1.5'])
# res = snmpwalk(ipaddress='202.119.11.12', oid='1.3.6.1.2.1.2.2.1.1')
# for line in res:
# 第一个元素为oid，第二个元素为对应的值
# print(line[0],'     ',line[1])

# res = snmptable(ipaddress='202.119.11.12', oid='1.3.6.1.2.1.6.13')
# print(res,type(res))
# for line in res:
#     print(line)
#
# res = snmpget(ipaddress='202.119.11.12', oid='1.3.6.1.2.1.1.1.0')
# print(res)

'''
描述，启动时间，接口数量
本机ip信息，ip接口，子网掩码,默认ttl
tcp端口，udp端口，snmp trap配置
'''
preIfInfo = {}
preErrPercent = []
dataBaseInfo = {}


# 获取交换机设备信息
def getSysInfo():
    result = {}
    res = snmpgetsome(ipaddress=setting.ipaddress, oids=[
        setting.sysDescri, setting.sysUpTime, setting.ifNumber,
        setting.ipDefaultTTL, setting.snmpEnableAuthenTraps])
    result['sysDescri'] = res[0][1]
    result['sysUpTime'] = timeTrans(res[1][1])
    result['ifNumber'] = int(res[2][1])
    result['ifType'] = {'normal': 24, 'AUI': 1, 'high': 2, 'PortChannel': 1}
    result['ipDefaultTTL'] = int(res[3][1])
    result['snmpEnableAuthenTraps'] = res[4][1]

    res = snmpwalk(ipaddress=setting.ipaddress, oid=setting.ipAddrTable)
    result['ipaddress'] = setting.ipaddress
    result['ipAdEntIfNum'] = int(res[1][1])
    result['ipNetMask'] = res[2][1]

    res = snmpgetsome(ipaddress=setting.ipaddress, oids=[
        setting.tcpRtoAlgorithm, setting.tcpRtoMax, setting.tcpMaxConn
    ])
    result['tcpRtoAlgorithm'] = res[0][1]
    result['tcpRtoMax'] = int(res[1][1].split(' ')[0])
    result['tcpMaxConn'] = int(res[2][1])

    res = snmpwalk(ipaddress=setting.ipaddress, oid=setting.tcpConnLocalPort)

    string = ', '
    result['tcpPort'] = []
    for line in res:
        result['tcpPort'].append(line[1])
    result['tcpPort'] = string.join(result['tcpPort'])

    res = snmpwalk(ipaddress=setting.ipaddress, oid=setting.udpLocalPort)
    result['udpPort'] = []
    for line in res:
        result['udpPort'].append(line[1])
    result['udpPort'] = string.join(result['udpPort'])
    return result


# 交换机启动时间
def getSysUpTime():
    res = snmpget(ipaddress=setting.ipaddress, oid=setting.sysUpTime)
    return timeTrans(res)


# 获取出错信息，出错率、出错包数、总包数   短
# ifInUcastPkts, ifInUNcastPkts, ifOutUcastPkts, ifOutUNcastPkts, ifInErrors,ifOutErrors
def getErrPercent():
    interfaceResult = []
    targets = [setting.ifInUcastPkts, setting.ifOutUcastPkts, setting.ifInUNcastPkts,
               setting.ifOutUNcastPkts, setting.ifInErrors, setting.ifOutErrors]
    targetStrs = ['ifInUcastPkts', 'ifOutUcastPkts', 'ifInUNcastPkts',
                  'ifOutUNcastPkts', 'ifInErrors', 'ifOutErrors']
    # 将各个端口数据get到
    for i in range(0, len(targets)):
        target = targets[i]
        targetStr = targetStrs[i]
        count = 0
        response = snmpwalk(ipaddress=setting.ipaddress, oid=target)
        for line in response:
            if len(interfaceResult) <= count:
                interfaceResult.append({'interface': count + 1})
            interfaceResult[count][targetStr] = int(line[1])
            count += 1

    # 对各个端口分别处理
    for i in range(0, len(interfaceResult)):
        res = interfaceResult[i]
        cal1 = calcuRate(
            [res['ifInErrors'], res['ifInUNcastPkts'], res['ifInUcastPkts']])
        interfaceResult[i]['inErrorRate'] = '{:.2%}'.format(cal1)
        dataBaseInfo['portList'][i]['inErrorRate'] = cal1
        cal2 = calcuRate(
            [res['ifOutErrors'], res['ifOutUNcastPkts'], res['ifOutUcastPkts']])
        interfaceResult[i]['outErrorRate'] = '{:.2%}'.format(cal2)
        dataBaseInfo['portList'][i]['outErrorRate'] = cal2

    return interfaceResult


# 获取单次轮询时计算利用率所需信息
def getIfInfo():
    result = {}
    ifResult = []
    # 记录数据库中所需端口信息
    portList = []
    # 前一次读取
    targetStrs = ['InOctets', 'OutOctets']
    IfsData = snmptable(ipaddress=setting.ipaddress, oid=setting.ifTable, timeout=3)
    count = 0
    for IfData in IfsData:
        ifResult.append(
            {'interface': count + 1, 'InOctets': int(IfData['ifInOctets']), 'OutOctets': int(IfData['ifOutOctets'])})
        uniPortDict = {'port': count + 1, 'ifInOctets': int(IfData['ifInOctets']),
                       'ifOutOctets': int(IfData['ifOutOctets']), 'ifInUcastPkts': int(IfData['ifInUcastPkts']),
                       'ifInNUcastPkts': int(IfData['ifInNUcastPkts']), 'ifOutUcastPkts': int(IfData['ifOutUcastPkts']),
                       'ifOutNUcastPkts': int(IfData['ifOutNUcastPkts']), 'ifInErrors': int(IfData['ifInErrors']),
                       'ifOutErrors': int(IfData['ifOutErrors'])}
        portList.append(uniPortDict)
        count += 1
    dataBaseInfo['portList'] = portList
    return ifResult


# 网段里主机信息
def getAtInfo():
    result = {}
    atInfoList = []
    atInfos = snmptable(ipaddress=setting.ipaddress, oid=setting.atTable, timeout=3)
    for atInfo in atInfos:
        uniAtInfoDict = {'connected_interface': atInfo['atIfIndex'],
                         'ip_address': ipTrans(atInfo['atNetAddress']),
                         'phys_address': atInfo['atPhysAddress']}
        atInfoList.append(uniAtInfoDict)
        # print(uniAtInfoDict)
    result['atResult'] = atInfoList
    return result


# 协议信息
def getProtocolInfo():
    result = {}
    dataBaseInfo['time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    # ip协议相关信息获取
    ipInfoList = []
    ipOids = [setting.ipInReceives, setting.ipOutRequests, setting.ipInDiscards, setting.ipOutDiscards,
              setting.ipInDelivers]
    ipInfos = snmpgetsome(ipaddress=setting.ipaddress, oids=ipOids, timeout=3)
    uniIpInfoDict = {'protocol': 'IP', 'ipInReceives': ipInfos[0][1], 'ipOutRequests': ipInfos[1][1],
                     'ipInDiscards': ipInfos[2][1],
                     'ipOutDiscards': ipInfos[3][1], 'ipInDelivers': ipInfos[4][1]}
    ipInfoList.append(uniIpInfoDict)
    result['ipInfo'] = ipInfoList
    dataBaseInfo['ipInReceives'] = int(ipInfos[0][1])
    dataBaseInfo['ipOutRequests'] = int(ipInfos[1][1])

    # tcp协议相关信息获取
    tcpInfoList = []
    tcpOids = [
        setting.tcpInSegs, setting.tcpOutSegs, setting.tcpRetransSegs, setting.tcpInErrs,
        setting.tcpEstabResets, setting.tcpActiveOpens, setting.tcpPassiveOpens, setting.tcpAttemptFails]
    tcpInfos = snmpgetsome(ipaddress=setting.ipaddress, oids=tcpOids, timeout=3)
    uniTcpInfoDict = {'protocol': 'TCP', 'tcpInSegs': tcpInfos[0][1], 'tcpOutSegs': tcpInfos[1][1],
                      'tcpRetransSegs': tcpInfos[2][1],
                      'tcpInErrs': tcpInfos[3][1],
                      'tcpEstabResets': tcpInfos[4][1],
                      'tcpActiveOpens': tcpInfos[5][1],
                      'tcpPassiveOpens': tcpInfos[6][1],
                      'tcpAttemptFails': tcpInfos[7][1]}
    tcpInfoList.append(uniTcpInfoDict)
    result['tcpInfo'] = tcpInfoList
    dataBaseInfo['tcpInSegs'] = int(tcpInfos[0][1])
    dataBaseInfo['tcpOutSegs'] = int(tcpInfos[1][1])

    # udp协议相关信息获取
    udpInfoList = []
    udpOids = [setting.udpInDatagrams, setting.udpOutDatagrams, setting.udpInErrors, setting.udpNoPorts]
    udpInfos = snmpgetsome(ipaddress=setting.ipaddress, oids=udpOids, timeout=3)
    uniUdpInfoDict = {'protocol': 'UDP', 'udpInDatagrams': udpInfos[0][1], 'udpOutDatagrams': udpInfos[1][1],
                      'udpInErrors': udpInfos[2][1], 'udpNoPorts': udpInfos[3][1]}
    udpInfoList.append(uniUdpInfoDict)
    result['udpInfo'] = udpInfoList
    dataBaseInfo['udpInDatagrams'] = int(udpInfos[0][1])
    dataBaseInfo['udpOutDatagrams'] = int(udpInfos[1][1])
    return result


# 接口速率
def getIfSpeed():
    setting.speedList = snmpwalk(ipaddress=setting.ipaddress, oid=setting.ifSpeed, timeout=3)


if __name__ == '__main__':
    # getIfSpeed()
    print([dict() * 29])
